package com.qf.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.entity.dto.ModuleRoleMiddle;
import com.qf.entity.dto.Role;
import com.qf.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;

@Service
public class RoleService extends ServiceImpl<RoleMapper, Role> {

    @Autowired
    private ModuleRoleMiddleService moduleRoleMiddleService;


    @Transactional
    public void saveRole(Role role, String moduleRoles) {
        //根据role的id是否为空来进行添加或删除role
        this.saveOrUpdate(role);

        //先删除ModuleRoleMiddle中间表中与roleId相关的记录
        if (role.getId() != null) {
            QueryWrapper<ModuleRoleMiddle> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(ModuleRoleMiddle::getRoleId, role.getId());
            moduleRoleMiddleService.remove(wrapper);
        }

        //再对ModuleRoleMiddle中间表进行批量插入记录
        String[] moduleIds = moduleRoles.split("|");
        List<ModuleRoleMiddle> linkedList = new LinkedList<>();
        for (String moduleId : moduleIds) {
            if (!"|".equals((moduleId))) {
                ModuleRoleMiddle adminModuleRole = new ModuleRoleMiddle();
                adminModuleRole.setRoleId(role.getId());
                adminModuleRole.setModuleId(Long.parseLong(moduleId));
                linkedList.add(adminModuleRole);
            }
        }
        moduleRoleMiddleService.saveBatch(linkedList, linkedList.size());
    }
}
